#!/usr/bin/env bash

include "libs/ohos.sh"
include "libs/regex.sh"
include "libs/output.sh"

function check_git()
{
    git remote 1>/dev/null 2>&1 || report "不在git仓库中"
    ORIGIN=$(git remote -v | grep "^o" | head -1 | awk '{print $2}')
    if [ "${ORIGIN:0:8}" = "https://" ] ; then
        ORIGIN=$(cut -d/ -f4 <<< $ORIGIN)
    else
        ORIGIN="$(cut -d: -f2 <<< $ORIGIN)"
        ORIGIN="$(cut -d/ -f1 <<< $ORIGIN)"
    fi
    local lang=$LANG
    CURBRANCH=$(LANG=en_US git branch | grep '^*' | cut -d' ' -f2)
    LANG=$lang
}

# dynamic.option --noname : git push不带名字
# --noname.option.list: git@push
dynamic_option:--noname()
{
    NONAME=1
    return 0
}

#help.cmd git@push [remote] [branch] : 往remote上推送分支，remote默认是passded，远程分支名默认是本地分支名
#alias.cmd ogp : git@push
dynamic_cmd:git:push()
{
    cd $COMMAND_CURDIR
    check_git || return
    local REMOTE=passded
    if (( $# >= 1 )); then
        REMOTE="$1"
        NONAME=1
    fi

    local url=$(git remote -v | grep "^o" | head -1 | awk '{print $2}' | sed "s/$ORIGIN/$REMOTE/g")
    git remote add $REMOTE $url 1>/dev/null 2>&1

    local username="$(git config user.name)-"
    if [ "$NONAME" = "1" ]; then
        username=""
    fi

    local REMOTE_BRANCH="${username}${CURBRANCH}"
    if (( $# >= 2 )); then
        REMOTE_BRANCH="$2"
    fi

    # 在push的时候不允许是HEAD
    if [ "${CURBRANCH:0:5}" = "(HEAD" ]; then
        MESSAGE="当前处于分离的头指针$(git branch | grep "^* " | awk '{$1=""; print $0}')"
        MESSAGE="$MESSAGE，请切换到本地具名分支上"
        false || report "$MESSAGE" || return
    fi

    echo "正在将本地分支($CURBRANCH)推到远程分支($REMOTE $REMOTE_BRANCH)上"
    git push -f $REMOTE ${CURBRANCH}:${REMOTE_BRANCH}
    report "正在将本地分支($CURBRANCH)推到远程分支($REMOTE/$REMOTE_BRANCH)上"
}

#help.cmd git@fetch [remote] branch : 从remote上拉取branch分支，remote默认是passded
#alias.cmd ogf : git@fetch
dynamic_cmd:git:fetch()
{
    local REMOTE="passded"
    local BRANCH

    check_git || return
    if (( $# == 0 )); then
        false || report "参数不全" || return
    elif (( $# == 1 )); then
        BRANCH=$1
    elif (( $# >= 2 )); then
        REMOTE=$1
        BRANCH=$2
    fi

    local url=$(git remote -v | grep "^o"| head -1 | awk '{print $2}' | sed "s/$ORIGIN/$REMOTE/g")
    git remote add $REMOTE $url 1>/dev/null 2>&1

    if [ "$CURBRANCH" = "$BRANCH" ]; then
        false || report "当前处于同名分支" || return
    fi

    git fetch -f $REMOTE $BRANCH:$BRANCH
    report "本地分支($BRANCH) 拉取自 远程分支($REMOTE/$BRANCH)" &&\
        echo "可以通过'git checkout $BRANCH'切换到对应分支上"
}

#help.cmd git@fetchpr [remote] id : 从remote上拉取PR，remote默认是默认远端
#alias.cmd ogfpr : git@fetchpr
dynamic_cmd:git:fetchpr()
{
    check_git || return
    if [ "$#" = "0" ]; then
        false || report "参数不全" || return
    fi
    if [ "$#" = "1" ]; then
        REMOTE=$ORIGIN
        BRANCHID=$1
    fi
    if [ "$#" = "2" ]; then
        REMOTE=$1
        BRANCHID=$2
    fi

    local url=$(git remote -v | grep "^o"| head -1 | awk '{print $2}' | sed "s/$ORIGIN/$REMOTE/g")
    git remote add $REMOTE $url 1>/dev/null 2>&1
    if [ "$CURBRANCH" = "$BRANCHID" ]; then
        false || report "当前处于同名分支" || return
    fi

    git fetch -f $REMOTE refs/pull/$BRANCHID/head:$BRANCHID
    report "本地分支($BRANCHID) 拉取自 PullRequest($BRANCHID)" &&\
        echo "可以通过'git checkout $BRANCHID'切换到对应分支上"
}

# dynamic.option --dry : git fetchissue不执行命令
# --dry.option.list: git@fetchissue
DRY=false
dynamic_option:--dry()
{
    DRY=true
    return 0
}

#help.cmd git@fetchissue issueurl : 从issueurl上拉取PR
#alias.cmd ogfis : git@fetchissue
dynamic_cmd:git:fetchissue()
{
    local commands=""

    ohos:cd_repo || return
    local issueurl="$1"
    if ! [[ "$issueurl" =~ (https://gitee.com/$regex_id/$regex_id/issues/$regex_issue) ]]; then
        output:loge "url不正确"
        return 1
    fi

    issueurl="${issueurl//\\/}"
    issueurl="${issueurl//\?*/}"
    issueurl+="/link_pull_request"
    output:logd "fetching $issueurl"
    if json="$(curl $issueurl 2>/dev/null)"; then
        output:logi "fetched $issueurl"
    else
        output:loge "cannot fetch $issueurl"
        return 1
    fi

    function get_json()
    {
        python -c "import sys, json; print(json.load(sys.stdin)$1)" <<< $json
    }

    function len_json()
    {
        python -c "import sys, json; print(len(json.load(sys.stdin)$1))" <<< $json
    }

    for (( i = 0; i < $(len_json "['data']"); i++ )); do
        local id="$(get_json "['data'][$i]['iid']")"
        local url="https://gitee.com$(get_json "['data'][$i]['path']")"
        output:logd "checking $url"
        if [[ $(curl $url 2>/dev/null) =~ (已关闭) ]]; then
            output:logi "closed"
            continue
        else
            output:logi "merging"
        fi

        local remote="${url//\/pulls*/}"
        local name="${remote//*\//}"
        local path="$(grep "name=\"$name\"" .repo/manifests/default.xml | sed 's/.*path="//g')"
        path="${path//\"*/}"
        local refs="${url//*\/pulls/refs\/pull}/head"

        if $DRY; then
            commands+="pushd $path\n"
            output:logd "git fetch -f $remote $refs:$id"
            commands+="git fetch -f $remote $refs:$id\n"
            commands+="git merge --no-edit $id\n"
            commands+="popd\n"
        else
            pushd $path >/dev/null
            while true; do
                output:logd "git fetch -f $remote $refs:$id"
                if git fetch -f $remote $refs:$id; then
                    output:logi "git fetch success"
                else
                    output:loge "git fetch failed"
                    continue
                fi
                break
            done
            git checkout $id
            popd >/dev/null
        fi
    done

    if $DRY; then
        echo -en "$commands"
    fi
}

#help.cmd git@delete [remote] branch : 把remote上的分支删除，remote默认是passded
#alias.cmd ogd : git@delete
dynamic_cmd:git:delete()
{
    check_git || return
    if [ "$#" = "0" ]; then
        false || report "参数不全" || return
    fi
    if [ "$#" = "1" ]; then
        REMOTE="passded"
        BRANCH=$1
    fi
    if [ "$#" = "2" ]; then
        REMOTE=$1
        BRANCH=$2
    fi

    local url=$(git remote -v | grep "^o"| head -1 | awk '{print $2}' | sed "s/$ORIGIN/$REMOTE/g")
    git remote add $REMOTE $url 1>/dev/null 2>&1
    git push -d $REMOTE refs/heads/$BRANCH
    report "删除$BRANCH分支"
}
